﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Threading;
using System.Web.SessionState;
using Pixysoft.Framework.Security;
using Pixysoft.Web;
using Pixysoft.Framework.Verifications;

namespace Pixysoft.Framework.Comet
{
    /// <summary>
    /// 让网站ajax获取信息 因为remoting无法同时开2个
    /// </summary>
    class CometHandler : IHttpHandler, IReadOnlySessionState
    {
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public virtual void ProcessRequest(HttpContext context)
        {
            string senderCode = StringHelper.GetSenderCode(context);

            if (!Verification.Verifies(senderCode).IsNotNullOrEmpty().Result())
            {
                LoggerHelper.Error("missing my name in request.");

                ICometMessage response = CometManager.CreateMessage("unknown", "unknown");

                CometManager.CometMessageHelper.SetText(response,
                    string.Format("get comet message error, missing senderCode:{0}.", senderCode));

                CometManager.CometMessageHelper.DoResponse(context.Response, response);

                return;
            }


            ICometMessage message = null;

            try
            {
                message = CometManager.CreateWebRemoting().GetCometMessage(senderCode, senderCode);
            }
            catch (Exception ex)
            {
                LoggerHelper.Fatal(ex);

                message = CometManager.CreateMessage("unknown", "unknown");

                CometManager.CometMessageHelper.SetText(message,
                    string.Format("get response error. {0}", ex.Message));
            }

            if (message == null)
            {
                message = CometManager.CreateMessage("unknown", "unknown");

                message.Content = new byte[] { };
            }

            CometManager.CometMessageHelper.DoResponse(context.Response, message);
        }
    }
}
